<template>
	<view class="m-2">
		<view class="bg-white p-2">
			<view class="d-flex flex-row flex-nowrap j-sb"
				style="width:670upx;height:80upx;line-height:80upx;border-bottom:2px solid #2878ff;font-size:30upx;">
				<view class="d-flex flex-row" style="width:160upx;line-height: 80upx;" @click="favorite">
					<image
						:src=" favoriteFlag == '1' ? '../../static/icon/favorite02.png' : '../../static/icon/favorite01.png' "
						style="width:40upx;height: 40upx;margin-top:15upx;margin-left:20upx;margin-right:10upx;">
					</image>
					<text>收藏</text>
				</view>
				<view class="d-flex flex-row flex-nowrap" style="width: 400upx;text-align: center;line-height: 80upx;">
					<view style="width:240upx;">
						考试剩余时间：
					</view>
					<view style="width: 200upx;">
						<uni-countdown :show-day="false" :second="remainedTime" @timeup="timeup" />
					</view>
				</view>

				<view class="d-flex flex-row flex-nowrap j-end" style="width:100upx;padding-right:20upx;"
					@click="showAnswerCard">
					<!--
					<text style="font-weight: bold;">{{currentIndex+1}}</text>/<text>{{ questionList.length }}</text>
					-->
					<image src="../../static/icon/abcd.png" style="width:30upx;height: 30upx;margin-top:25upx;margin-left:10upx;"></image>

				</view>
			</view>
			<view style="height: 80upx;line-height: 80upx;font-size:32upx;">
				<view style="font-weight: bold;"> {{ currentChapterName }} {{ questionSubIndexShow }}</view>
			</view>

			<swiper class="swiper" style="height: 900upx;" :current="currentIndex" @change="questionChange">
				<swiper-item v-for="(item,index) in questionList" :key="'q' + item.id">
					<scroll-view scroll-y="true" style="height: 1000upx;">
						<view style="width:670upx;font-size:32upx;">
							<!-- 选择题 -->
							<view>
								<view class="mt-2">
									<rich-text v-html="item.title" ></rich-text>
									<!--
									<text style="color:red;font-weight: bold;">{{item.standardAnswer}}</text>
									-->
								</view>
								<view v-for="(sitem,sindex) in item.questionOptions" :key="sitem.id"
									class="d-flex flex-row flex-wrap mt-2 option_con"
									:style=" 'background-color:' + ( (currentOptionId && currentOptionId.indexOf(sitem.id) != -1) ? '#019ef8' : '#f2f2f2') + ';color:' + ( (currentOptionId && currentOptionId.indexOf(sitem.id) != -1) ? '#ffffff' : '#000000')+ ';'"
									@click="selectOption(item.id, sitem.id)">
									<view class="option_no">
										<text>{{ sitem.letter }}</text>
									</view>
									<view class="d-flex flex-row flex-wrap py-1 pr-1" style="width:590upx;">
										<rich-text v-html="sitem.optionContent" ></rich-text>
									</view>
								</view>

							</view>
						</view>
					</scroll-view>
				</swiper-item>
			</swiper>

			
			<view class="d-flex flex-row flex-nowrap j-sb mt-2">
				<view class="w-50 pr-2">
					<button :class="this.currentIndex > 0 ? 'pre_next_enable_btn' : 'pre_next_disabled_btn' "
						@click="preview">上一题</button>
				</view>
				<view class="w-50 pl-2">
					<button
						:class=" this.currentIndex < this.questionList.length - 1 ? 'pre_next_enable_btn' : 'pre_next_disabled_btn' "
						@click="next">下一题</button>
				</view>
			</view>

			<view style="margin-top:20upx;">
				<button class="main_btn" @click="manualSubmitPaper">提交试卷</button>
			</view>
		</view>

		<answer_card v-show="showCard" style="width:670upx;position: absolute; top:120upx;left:40upx;"
			:chapterList="chapterList" :currentIndex="currentIndex" @selectEvent="handleSelect"></answer_card>

		<uni-popup ref="submitConfirmDialog" type="dialog">
			<uni-popup-dialog type="error" cancelText="取消" confirmText="确定" title="提醒" content="你有尚未答案题目,确认要提交吗？" @confirm="confirmSubmit"
			@close="confirmClose"></uni-popup-dialog>
		</uni-popup>
		
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 考试剩余时间
				remainedTime: 0,
				nowTime: '00:56:23',
				// 显示答题卡
				showCard: false,
				// 提交标识（提交后又回退到考试页面跳转首页）
				submitFlag: "0",
				// 当前正在进行的专题id
				answerPaperId: '',
				paperName: '',
				// 考生ID
				staffId: '',
				// 模拟试卷ID
				paperId: '',

				// 当前大题
				currentChapterName: '',

				questionList: [],
				// 当前试题编号索引
				currentIndex: 0,
				// 当前刷题进度
				questionSubIndexShow: '',
				// 答题卡
				chapterList: [],
				// 选中的答案
				currentOptionId: '',

				// 标题答案和解析
				showAnswerAnslysis: false,
				standardAnswer: '', 
				analysis: '', 

				// 当前试题是否收藏
				favoriteFlag: false,

				// 最后答题序号
				endIndex: 0,
			}
		},

		onShow() {
			console.log('submitFlag:' + this.submitFlag)
			// 如果已经提交试卷，跳转首页
			if (this.submitFlag == "1") {
				uni.switchTab({
					url: "/pages/index/index"
				})
			}
		},

		onLoad(option) {
			this.answerPaperId = option.answerPaperId
			this.staffId = option.staffId
			this.paperId = option.paperId
			// 考试剩余时间
			this.remainedTime = parseInt(option.remainedTime)
			this.getSimulateData()
		},
		
		onReady() {
		    // 页面加载完成后禁用滚动
		    document.body.style.overflow = 'hidden';
		    document.documentElement.style.overflow = 'hidden';
		},
		
		methods: {

			// 查询模拟试卷信息
			getSimulateData() {
				let url = '/moni/getSumilatePaperQuestion'
				let param = {
					id: this.answerPaperId,
					staffId: this.staffId,
					paperId: this.paperId
				}

				this.$H.post(url, param, {
					token: true
				}).then(res => {
					if (!res || res.code != 200) {
						return uni.showToast({
							title: '获取数据失败'
						})
					}
					uni.hideLoading()
					this.questionList = res.result.questionList
					this.chapterList = res.result.chapterList


					// 处理当前进行到第几题
					this.endIndex = res.result.endIndex
					
					// 直接跳转到上次刷题的进度
					this.currentIndex = (this.endIndex && this.endIndex < this.questionList.length - 1) ? this
						.endIndex : 0

					// 当时刷题序号进度
					let question = this.questionList[this.currentIndex]
					this.questionSubIndexShow = question.questionSubIndexShow


					let chapterId = question.chapterId
					let chapter = this.chapterList.filter(item => item.id == chapterId)[0]

					// 当前大题
					this.currentChapterName = chapter.title

					// 收藏标记
					let currentAnswer = chapter.answerList.filter(item => item.questionId == question.id)[0]
					this.favoriteFlag = currentAnswer.favoriteFlag

					// 当前试题的答案显示
					this.currentOptionId = currentAnswer.staffAnswerId


				}).catch(err => {
					if (err.msg) {
						uni.showToast({
							title: err.msg,
							icon: 'none'
						})
					}
					uni.hideLoading()
				})
			},
			// 选择答案
			selectOption(questionId, optionId) {
				let question = this.questionList.filter(item => item.id == questionId)[0]
				let option = question.questionOptions.filter(sitem => sitem.id == optionId)[0]
				
				let chapterId = question.chapterId
				let chapter = this.chapterList.filter(item => item.id == chapterId)[0]
				let currentAnswer = chapter.answerList.filter(item => item.questionId == question.id)[0]
				
				
				// 试题类型 1 单选 2 多选  3 判断  4 案例
				let questionType = question.questionType
				
				let isRight = null
				let staffAnswerId = null
				let staffAnswer = null
				let currentOptionId = null
				
				let t1 = new Date()
				// 修改答题卡答对、答错颜色
				if(questionType == '1' || questionType == '3'){
					// 修改答题卡答对、答错颜色
					isRight = question.standardAnswer == option.letter ? "1" : "0"
					staffAnswerId = optionId
					staffAnswer = option.letter
					currentOptionId = optionId
				}else if(questionType == '2' || questionType == '4'){
					// 原始答案
					let oldAnswer = currentAnswer.staffAnswer
					let oldAnswerId = currentAnswer.staffAnswerId
					
					let oldAnswerArr = oldAnswer ? oldAnswer.split(',') : []
					let oldAnswerIdArr = oldAnswerId ? oldAnswerId.split(','):[]
					
					if(oldAnswerId && oldAnswerId.indexOf(optionId) != -1){
						// 清除已选选项
						oldAnswerArr = oldAnswerArr.filter(item => item != option.letter)
						oldAnswerIdArr = oldAnswerIdArr.filter(item => item != optionId)
					}else if(!oldAnswerId || oldAnswerId.indexOf(optionId) == -1){
						// 添加未选中的选项
						oldAnswerIdArr.push(optionId)
						oldAnswerArr.push(option.letter)
					}
					
					staffAnswerId = oldAnswerIdArr.join(',')
					oldAnswerArr.sort()
					staffAnswer = oldAnswerArr.join(',')
					currentOptionId = oldAnswerIdArr.join(',')
					// 完全匹配算正确
					isRight = (question.standardAnswer == oldAnswerArr.join(',')) ? "1" : "0"
				}
				
				let t2 = new Date()
				console.log('dom操作耗时:' + (t2 - t1))
				
				// 等请求结束后再赋值时，用户体验会有一定延时，所以先赋值
				this.currentOptionId = currentOptionId
				
				let url = '/moni/answerQuestion'
				let param = {
					answerPaperId: this.answerPaperId,
					staffId: this.staffId,
					paperId: this.paperId,
					chapterId: question.questionCategory,
					questionId: questionId,
					questionScore: question.defaultScore,
					staffAnswer: staffAnswer,
					staffAnswerId: staffAnswerId,
					standardAnswer: question.standardAnswer,
					isRight: isRight,
					endIndex: this.currentIndex,
				}
				this.$H.post(url, param, {
					token: true
				}).then(res => {
					
					let t3 = new Date()
					
					console.log('dom操作耗时2:' + (t3-t2))
					
					if (!res || res.code != 200) {
						return uni.showToast({
							title: '操作异常',
							icon: 'none'
						})
					}

					// 修改答题卡答对、答错颜色
					currentAnswer.isRight = isRight
					currentAnswer.staffAnswerId = staffAnswerId
					currentAnswer.staffAnswer = staffAnswer
					
					// this.currentOptionId = currentOptionId

				}).catch(err => {
					if (err.msg) {
						uni.showToast({
							title: err.msg,
							icon: 'none'
						})
					}
				})
			},
			// 试题切换
			questionChange(event) {
				this.currentIndex = event.detail.current
				this.statusSwip()
			},
			// 定位试题
			handleSelect(param) {
				let questionId = param.questionId
				let index = param.index
				// 定位到试题
				this.currentIndex = index
				this.statusSwip()
				// 切换试题后隐藏答题卡
				this.showCard = false
			},

			showAnswerCard() {
				this.showCard = !this.showCard
			},


			// 下一题
			next() {
				if (this.currentIndex < this.questionList.length - 1) {
					++this.currentIndex;
					this.statusSwip()
				}
			},
			// 上一题
			preview() {
				if (this.currentIndex > 0) {
					--this.currentIndex
					this.statusSwip()
				}
			},

			// 切换试题数据状态变更 
			statusSwip() {

				// 当时刷题序号进度
				let question = this.questionList[this.currentIndex]

				// 初始化当前试题的收藏
				let chapterId = question.chapterId
				let chapter = this.chapterList.filter(item => item.id == chapterId)[0]

				// 当前大题
				this.currentChapterName = chapter.title

				let currentAnswer = chapter.answerList.filter(item => item.questionId == question.id)[0]

				// 前端试题的考生答案显示
				this.currentOptionId = currentAnswer.staffAnswerId

				// 收藏状态
				this.favoriteFlag = currentAnswer.favoriteFlag

				// 当时刷题进度
				this.questionSubIndexShow = question.questionSubIndexShow

				// 隐藏解析
				this.showAnswerAnslysis = false
			},

			// 收藏或取消收藏
			favorite() {
				let question = this.questionList[this.currentIndex]

				let chapterId = question.chapterId
				let chapter = this.chapterList.filter(item => item.id == chapterId)[0]
				let currentAnswer = chapter.answerList.filter(item => item.questionId == question.id)[0]


				this.favoriteFlag = currentAnswer.favoriteFlag == "1" ? false : true
				currentAnswer.favoriteFlag = currentAnswer.favoriteFlag == "1" ? "0" : "1"
				let url = currentAnswer.favoriteFlag == "1" ? "/moni/favorite" : "/moni/unfavorite"
				let param = {
					answerPaperId: this.answerPaperId,
					staffId: this.staffId,
					chapterId: chapterId,
					questionId: question.id,
					faviroteType: '1',
				}
				this.$H.post(url, param, {
					token: true
				}).then(res => {
					if (!res || res.code != 200) {
						return uni.showToast({
							title: '操作失败',
							icon: 'none'
						})
					}
				}).catch(err => {
					if (err.msg) {
						uni.showToast({
							title: err.msg,
							icon: 'none'
						})
					}
				})

			},
			
			// 确认提交试卷
			confirmSubmit() {
				this.submitPaper()
			},
			// 取消提交
			confirmClose(){
				
			},
			
			// 判断是否有未答题目
			hasNotAnswerQuestion(){
				let existsNotAnswer = false;
				this.chapterList.forEach(item=>{
					item.answerList.forEach(sitem=>{
						if(!sitem.staffAnswer){
							return 1;
						}
					})
				})
				return 0;
			},
			
			// 手动提交试卷
			manualSubmitPaper(){
				// 检查是否有未答题目，如果有则提示
				let hasNotAnswerFlag = this.hasNotAnswerQuestion()
				if(hasNotAnswerFlag == 1){
					this.$refs.submitConfirmDialog.open()
				}else{
					this.submitPaper()
				}
			},

			// 提交试卷
			
			submitPaper() {
				let url = "/moni/submitPaper"
				let param = {
					staffId: this.staffId,
					id: this.answerPaperId,
				}
				this.$H.post(url, param, {
					token: true
				}).then(res => {
					if (!res || res.code != 200) {
						return uni.showToast({
							title: '操作失败'
						})
					}

					this.submitFlag = '1'

					// 提交成功，跳转考试结果页面
					uni.navigateTo({
						url: '/pages/moni/moni_grade?id=' + this.answerPaperId
					})

				}).catch(err => {
					if (err.msg) {
						uni.showToast({
							title: err.msg,
							icon: 'none'
						})
					}
					uni.hideLoading()
				})
			},

			// 考试时间结束
			timeup() {
				uni.showToast({
					title: '答题时间到，正在提交试卷',
					icon: 'none'
				})
				setTimeout(()=>{
					// 强制提交试卷
					this.submitPaper()
				}, 1000)
			}

		}
	}
</script>

<style>
	page {
		height: 100%;
		background: #f1f1f1;
	}

	.option_con {
		background-color: #f2f2f2;
	}

	.option_con_selected {
		background-color: #c5dcf2;
	}

	.option_no {
		width: 50upx;
		margin-left: 20upx;
		padding-top: 10upx;
	}

	.pre_next_enable_btn {
		height: 70upx;
		line-height: 70upx;
		border-radius: 35upx;
		font-size: 28upx;
		background-color: #2878ff;
		color: #ffffff;
	}

	.pre_next_disabled_btn {
		height: 70upx;
		line-height: 70upx;
		border-radius: 35upx;
		font-size: 28upx;
		background-color: #d6d6d6;
	}

	.view_btn {
		height: 70upx;
		line-height: 70upx;
		border-radius: 35upx;
		color: #ffffff;
		background-color: #2878ff;
		font-size: 28upx;
		width: 300upx;
	}
</style>